package br.com.frbb.ugvbr.image;

import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import android.graphics.Bitmap;
import android.util.Log;

public class ImageFilter {
	
	private final String TAG = this.getClass().getName();
	
	private static final Size GAUSSIAN_SIZE = new Size(3, 3);
	private static final int GAUSSIAN_SIGMAX = 2;
	private static final int GAUSSIAN_SIGMAY = 2;
	
	private static final int THRESHOLD_LIMIAR = 115;
	private static final int THRESHOLD_MAX = 255;
	private static final int THRESHOLD_TYPE = Imgproc.THRESH_BINARY;
	
	private static final Size FINAL_SIZE = new Size(13, 20);
	
	ImageFilter() { }

	public Bitmap applyFilters(Mat mat) {
		
		Mat color = new Mat();
		Bitmap bitmap;
		
		// Aplica filtros
		Imgproc.GaussianBlur(mat, mat, GAUSSIAN_SIZE, GAUSSIAN_SIGMAX, GAUSSIAN_SIGMAY);
        Imgproc.threshold(mat, mat, THRESHOLD_LIMIAR, THRESHOLD_MAX, THRESHOLD_TYPE);
        
        // Redimensiona imagem
        Imgproc.resize(mat, mat, FINAL_SIZE);
		
        // Converte para colorido e cria bitmap
		Imgproc.cvtColor(mat, color, Imgproc.COLOR_GRAY2RGB, 4);
        bitmap = Bitmap.createBitmap(color.cols(), color.rows(), Bitmap.Config.RGB_565);
        
        // Converte Mat para Bitmap
        try {
        	Utils.matToBitmap(color, bitmap);
            return bitmap;
        } catch(Exception e) {
        	Log.e(TAG, "Error on converting Mat to Bitmap: " + e.getMessage());
        	bitmap.recycle();
            return null;
        }
	}
}
